package com.shure.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.ConvertException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyu
 * @date 2021/08/18 15:37
 */
public class CloneUtil {
    private CloneUtil() {
    }

    public static <T> T clone(Object source, Class<T> clazz) {
        try {
            if (source == null) {
                return null;
            } else {
                T bean = clazz.getDeclaredConstructor().newInstance();
                BeanUtil.copyProperties(source, bean);
                return bean;
            }
        } catch (
                Exception var3) {
            throw new ConvertException(var3);
        }
    }

    public static <T> List<T> cloneList(List<?> source, Class<T> clazz) {
        List<T> resultList = new ArrayList<>();
        if (!CollUtil.isEmpty(source)) {
            for (Object ele : source) {
                resultList.add(clone(ele, clazz));
            }
        }
        return resultList;
    }

    public static <T> Page<T> clonePage(Page<T> source, Class<T> clazz) {
        Page<T> resultPage = new Page<>();
        List<T> resultList = source.getRecords();
        if (!CollUtil.isEmpty(resultList)) {
            for (Object ele : resultList) {
                resultList.add(clone(ele, clazz));
            }
            resultPage.setRecords(resultList);
        }
        return resultPage;
    }
}
